package lhxia.translater.http.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.concurrent.LinkedBlockingQueue;

import lhxia.translater.http.server.HttpServer.ServerAttach;
import lhxia.translater.http.server.ThreadPool.WokerThread;
import lhxia.translater.http.server.ThreadPool.WokerThread.Attach;

public class ServerProcessor {
	
	public static final String TAG = ServerProcessor.class.getName();
	
	public void onNewConnection(SocketChannel connection, SelectionKey keys) throws IOException{
		Pipe pip = Pipe.open();
		pip.sink().configureBlocking(false);
		pip.source().configureBlocking(false);
		Object[] o = ThreadPool.getInstance().submit(connection, pip);
		ServerAttach atta = new ServerAttach(pip, (WokerThread)o[0], (Attach)o[1], connection, keys);
		keys.attach(atta);
	}
	
	public boolean onRead(SocketChannel connection, SelectionKey keys) throws IOException{
		ServerAttach att = (ServerAttach) keys.attachment();
		ByteBuffer buffer = BufferPool.getInstance().getBuffer();
		int count = connection.read(buffer);
		if(count == -1){
			connection.close();
			BufferPool.getInstance().backBuffer(buffer);
			return false;
		}
		buffer.flip();
		att.getThread().put(att.getPip(), buffer);
		BufferPool.getInstance().backBuffer(buffer);
		return true;
	}
	
	public void onDisconnected(SocketChannel connection, SelectionKey keys){
		ServerAttach att = (ServerAttach) keys.attachment();
		att.getThread().disattachConnect(att.getAtt());
	}
	
}